package com.aimei520.controller;

import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aimei520.po.admin.User;
import com.aimei520.po.meun.Menu;
import com.aimei520.service.api.LoginService;
import com.aimei520.utils.HostInfo;
import com.aimei520.utils.JsonResult;

/**
 * 登录控制器，用于用户登录，用户注册，用户登录后菜单生成
 * <p>Title: LoginController.java</p>  
 * <p>Description: </p>  
 * <p>Copyright: Copyright (c) 2018</p>  
 * <p>Company: www.storyboy.xyz</p>  
 * @author JiaXun  
 * @date 2018年8月31日  
 * @version 1.0.0
 */
@Controller
@RequestMapping("/login")
public class LoginController {
	
	@Resource
	private LoginService loginService;
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String loginViewPage() {
		return "login/login";
	}
	
	@ResponseBody
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public JsonResult login(User user,HttpServletRequest request) {
		JsonResult result = new JsonResult(true, "登录成功");
		try {
			if(!loginService.doLogin(user,request.getSession())) {
				result.setSuccess(false);
				result.setMsg("登录失败,账号或密码错误");
			}
		} catch (NoSuchAlgorithmException e) {
			result.setSuccess(false);
			result.setMsg("登录失败");
		}
		
		return result;
	}
	
	@RequestMapping("/home")
	public String homeViewPage(Model model,HttpServletRequest request) {
		
		if(request.getSession().getAttribute("menu") != null) {
			List<Menu> menu = (List<Menu>) request.getSession().getAttribute("menu");
			model.addAttribute("menu",menu);
		}
		return "login/home";
	}
	
	@RequestMapping("/welcome")
	public String welcomeViewPage(Model model,HttpServletRequest request) throws UnknownHostException {
		User user_session = (User) request.getSession().getAttribute("user");
		model.addAttribute("user",user_session);
		model.addAllAttributes( HostInfo.getHostInfo(request) );
		return "login/welcome";
	}
	
	@RequestMapping("/error")
	public String errorPageView() {
		
		return "login/error";
	}
	
}
